package com.example.demo.core.util;

import com.example.demo.core.exception.ProgramException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yujie
 * @date 2021-04-17 12:19
 */
public class ByteUtil {

    private Logger logger = LoggerFactory.getLogger(ByteUtil.class);

    /**
     * byte数组转换城String数组
     */
    public static List<String> byteArrayToStringArray(byte[] bytes) {
        List<String> list = new ArrayList<>();
        for (byte it : bytes) {
            int o = it;
            if (o < 0) {
                o = it + 256;
            }
            String data = Integer.toHexString(o).toUpperCase();
            data = (data.length() < 2) ? "0" + data : data;
            list.add(data);
        }
        return list;
    }

    /**
     * 字符串转byte数组
     */
    public static byte[] toByteArray(String hexString) {
        if (RegexUtil.checkStringIsNull(hexString)) {
            throw new ProgramException("参数不能为空");
        }
        String hex = hexString.toLowerCase();
        byte[] byteArray = new byte[hex.length() / 2];
        int k = 0;
        for (int i = 0; i < byteArray.length; i++) {
            byte high = (byte) (Character.digit(hex.charAt(k), 16) & 255);
            byte low = (byte) (Character.digit(hex.charAt(k + 1), 16) & 255);
            byteArray[i] = (byte) ((int) (high) << 4 | (int) (low));
            k += 2;
        }
        return byteArray;
    }

}
